package com.auto.learning.fragment;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.os.Bundle;
import android.os.Handler.Callback;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.auto.learning.R;
import com.auto.learning.activity.SearchActivity;
import com.auto.learning.adapter.VideoPageAdapter;
import com.auto.learning.bean.ResponeResult;
import com.auto.learning.bean.VideoBean;
import com.auto.learning.event.Handle;
import com.auto.learning.net.Cache;
import com.auto.learning.net.HttpCommonInfo;
import com.auto.learning.net.HttpRequestHelper;
import com.auto.learning.sharesdk.tools.ShareOpUtils;
import com.auto.learning.tools.CommonMethod;
import com.auto.learning.view.PullToRefreshListView;
import com.auto.learning.view.ShareView;
import com.auto.learning.view.PullToRefreshListView.OnRefreshListener;
import com.auto.learning.view.SharedPreferencesUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class SearchMrtFragment extends Fragment implements Callback {

	public final static int SHARE = 2;
	
	private PullToRefreshListView listview_s_mrt;
	private VideoPageAdapter adapter;
	private ArrayList<VideoBean> list = new ArrayList<VideoBean>();
	
	private View lvProductFooter;
	private TextView lvProductFooterMore,tv_data_empty;
	private ProgressBar lvProductFooterProgress;
	private TextView lvBtn_more;
	private LinearLayout lvLinear_more;
	
	private int pageIndex = 0;
	
	private RelativeLayout relative_main;
	
	private Handle handler = new Handle(getActivity()){
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case HttpRequestHelper.GETDATA_SUCCESS:
				String bottom = "";
				ResponeResult result =(ResponeResult) msg.obj;
				ArrayList<VideoBean> resultList = new Gson().fromJson(result.getData(), new TypeToken<ArrayList<VideoBean>>() {}.getType());
				if (pageIndex == 0) {
					list.clear();
					list.addAll(resultList);
					Cache.cacheVideo2Local(resultList);
				} else {
					list.addAll(resultList);
				}
				if (resultList.size() >= 10) {
					pageIndex ++;
					lvBtn_more.setVisibility(View.VISIBLE);
					lvProductFooterMore.setText(bottom);
				} else {
					bottom = getResources().getString(R.string.text_video_data);
					lvLinear_more.setVisibility(View.VISIBLE);
					lvProductFooterMore.setText(bottom);
					lvProductFooterProgress.setVisibility(View.GONE);
					lvBtn_more.setVisibility(View.GONE);
				}
				
				if (listview_s_mrt != null) {
					listview_s_mrt.onRefreshComplete();
					listview_s_mrt.setTag(0);
				}
				if (list != null && list.size() > 0) {
					adapter.notifyDataSetChanged();
				}
				break;
			case HttpRequestHelper.GETDATA_FAIL:
				CommonMethod.makeNotice(getActivity(), msg.obj.toString());
				if (listview_s_mrt != null) {
					listview_s_mrt.onRefreshComplete();
					listview_s_mrt.setTag(0);
				}
				break;
			case SHARE:
				VideoBean mVideoBean = (VideoBean) msg.obj;
				if (mVideoBean != null) {
					String url = HttpCommonInfo.MURL +"video-detail?id=" + mVideoBean.getId();
					String title = mVideoBean.getTitle();
					new ShareView(getActivity(), SearchMrtFragment.this).setTitle(title).setUrl(url).setContent(mVideoBean.getSlogan()).setImageUrl(mVideoBean.getVideoImg()).setId(mVideoBean.getId()+"").setType(2).show(relative_main);
				}
				break;
			}
		};
	};
	
	private String getKey(){
		return ((SearchActivity)getActivity()).getKey();
	}
 	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_s_mrt, null);
		initView(view);
		return view;
	}
	
	
	private void initView(View view){
		relative_main = (RelativeLayout) view.findViewById(R.id.relative_main);
		tv_data_empty = (TextView) view.findViewById(R.id.tv_data_empty);
		lvProductFooter = getActivity().getLayoutInflater().inflate(R.layout.listview_footer, null);
		lvProductFooterMore = (TextView) lvProductFooter.findViewById(R.id.listview_foot_more);
		lvProductFooterProgress = (ProgressBar) lvProductFooter.findViewById(R.id.listview_foot_progress);
		lvBtn_more = (TextView) lvProductFooter.findViewById(R.id.btn_more);
		lvLinear_more = (LinearLayout) lvProductFooter.findViewById(R.id.linear_more);
		
		listview_s_mrt = (PullToRefreshListView) view.findViewById(R.id.listview_s_mrt);
		adapter = new VideoPageAdapter(getActivity(), list, handler);
		listview_s_mrt.setAdapter(adapter);
		listview_s_mrt.setTag(0);
		
		listview_s_mrt.setOnRefreshListener(new OnRefreshListener() {
			
			@Override
			public void onRefresh() {
				pageIndex = 0;
				getData(getKey());
			}
		});
		
		listview_s_mrt.addFooterView(lvProductFooter);
		lvBtn_more.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				getData(getKey());
			}
		});
		listview_s_mrt.setOnScrollListener(new OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				listview_s_mrt.onScrollStateChanged(view, scrollState);
				boolean scrollEnd = false;
				try {
					if (view.getPositionForView(lvProductFooter) == view.getLastVisiblePosition()
							&& !lvProductFooterMore.getText().toString().equals(getResources().getString(R.string.text_video_data))) {
						scrollEnd = true;
					}
				} catch (Exception e) {
					scrollEnd = false;
				}
				
				int lvDataState = Integer.parseInt((listview_s_mrt.getTag().toString()));
				if (scrollEnd && lvDataState == 0) {
					listview_s_mrt.setTag(1);
					lvProductFooterMore.setText("加载中");
					lvProductFooterProgress.setVisibility(View.VISIBLE);
					lvLinear_more.setVisibility(View.VISIBLE);
					lvBtn_more.setVisibility(View.GONE);
					int page = listview_s_mrt.getCount() - 2;  // 减去ListView的头和尾的
					getData(getKey());
				}
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				listview_s_mrt.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);
			}
		});
		
	}
	
	
	
	public void setList(ArrayList<VideoBean> m_list) {
		list.clear();
		if (m_list != null && m_list.size() > 0) {
			list.addAll(m_list);
			pageIndex ++;
		}else {
			pageIndex = 0;
		}
		if (adapter != null) {
			adapter.notifyDataSetChanged();
			lvProductFooterMore.setText("");
		}
		
		if (list == null || (list != null && list.size() == 0)) {
			tv_data_empty.setVisibility(View.VISIBLE);
			listview_s_mrt.setVisibility(View.GONE);
		}else {
			tv_data_empty.setVisibility(View.GONE);
			listview_s_mrt.setVisibility(View.VISIBLE);
		}
	}
	
	private void getData(String key){
		if (TextUtils.isEmpty(key)) {
			if (listview_s_mrt != null) {
				listview_s_mrt.onRefreshComplete();
			}
			return;
		}
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(HttpRequestHelper.USERID, String.valueOf(SharedPreferencesUtils.getParam(getActivity(), HttpRequestHelper.USERID, 0))));
		params.add(new BasicNameValuePair("key", key+""));
		params.add(new BasicNameValuePair("pageIndex",String.valueOf(pageIndex)));
		HttpRequestHelper.executeHttpData(getActivity(), HttpRequestHelper.SEARCH_ALL_HOF, params, handler, HttpRequestHelper.GETDATA_SUCCESS, HttpRequestHelper.GETDATA_FAIL);
	}

	@Override
	public boolean handleMessage(Message msg) {
		ShareOpUtils.handleShareCallBack(getActivity(), msg);
		return false;
	}
	
	
}
